﻿using System.Reflection;
using System.Web.UI;
using JQuery.WebKit.Common.Extenstions;
using JQuery.WebKit.Common.Utilities;
using JQuery.WebKit.WebCommon.Attributes;

namespace JQuery.WebKit.WebCommon.Javascript
{
    public static class JsProperties
    {
        public static string GetProperties(Control controlInstance)
        {
            string propStr = string.Empty;

            PropertyInfo[] props = controlInstance.GetType().GetFilteredProperties(BindingFlags.Public | BindingFlags.Instance);

            bool hasCollectionProps = false;
            foreach (PropertyInfo info in props)
            {
                JavaScriptAttribute jsAtt = (JavaScriptAttribute)Reflection.GetAttribute(controlInstance, info, typeof(JavaScriptAttribute));
                if (jsAtt == null)
                {
                    continue;
                }
                
                object value = Reflection.GetValue(controlInstance, info, true, false);
                if (value == null)
                {
                    continue;
                }

                if (value.Equals(jsAtt.DefaultValue))
                {
                    continue;
                }

                string jsName = info.JSName().Trim();
                string jsValue = value.ToJSString().Trim();
                if (!string.IsNullOrEmpty(jsName) && !string.IsNullOrEmpty(jsValue))
                {
                    propStr += string.Format("{0}: {1}, ", jsName, jsValue);
                    hasCollectionProps = true;
                }
                else if (!string.IsNullOrEmpty(jsValue))
                {
                    propStr += string.Format("{0}, ", jsValue);
                }
            }

            if (propStr.Length > 0)
            {
                propStr = propStr.Substring(0, propStr.Length - 2);
                if (hasCollectionProps)
                {
                    propStr = string.Format("{{{0}}}", propStr);
                }
            }

            return propStr;
        }

        public static string Append(string propertyCollection, string property)
        { 
            if (string.IsNullOrEmpty(property))
            {
                return propertyCollection;
            }

            if (propertyCollection.EndsWith("}"))
            {
                propertyCollection = propertyCollection.Substring(0, propertyCollection.Length - 1);
            }

            propertyCollection += string.Format(", {0}}}", property);

            return propertyCollection;
        }
    }
}
